package com.fingard.dsp.bank.directbank.zjrb01;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by aaron on 2018/4/26.
 */
public class ZJRB01Transaction extends ZJRB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAtsTrans.writeStart();

        try {
            //tmpClndrStepTo.get(Calendar.MONTH) MONTH是从0开始编的，意味着0是1月，11是12月
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            //int qryCount=0;
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                String opName = "BSHisDetailOp";
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                writeCommenHeader(xmlTextWriter, opName);
                XElement ReqParam = new XElement("ReqParam","");
                ReqParam.addChild(new XElement("Area_code",p_req7516.actArea));
                ReqParam.addChild(new XElement("Account_num",p_req7516.actNum));
                ReqParam.addChild(new XElement("Account_cur",convertCurToBank(p_req7516.actCur)));
                ReqParam.addChild(new XElement("Begin_date",Format.Date8Format.format(tmpCalendarFrom.getTime())));
                ReqParam.addChild(new XElement("End_date",Format.Date8Format.format(tmpClndrStepTo.getTime())));
                ReqParam.addChild(new XElement("Max_amount",""));//最大金额
                ReqParam.addChild(new XElement("Min_amount",""));//最小金额
                ReqParam.addChild(new XElement("userID",bankFront.loginName));
                ReqParam.addChild(new XElement("PackageID",getQryTransID()));
                ReqParam.addChild(new XElement("RepReserved1",""));
                ReqParam.addChild(new XElement("RepReserved2",""));
                wirteReqBody(xmlTextWriter, ReqParam, null);
                xmlTextWriter.writeEndDocument();
                String[] bankResult = sendToBank(xmlTextWriter.toXmlString());
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String retCode = tmpBkReader.getFirstText("/ROOT/opRep/opResult/retCode");
                        if ("0".equals(retCode)) {
                            while (tmpBkReader.read("/ROOT/opRep/opResultSet/opResult")) {
                                XElement readXElement = tmpBkReader.readedXElement;
                                RetAtsTransDetail detail = new RetAtsTransDetail();
                                detail.tranDate = DateHelper.convertD8toD10(readXElement.getSingleTextNotNull("Trans_date").trim());
                                detail.valueDate = detail.tranDate;
                               // yyyy-MM-dd-HH:mm:ss:6位毫秒 共26位
                                detail.tranTime = detail.tranDate+" "+readXElement.getSingleTextNotNull("Trans_time").substring(11, 19);
                                detail.actNum = readXElement.getSingleTextNotNull("Account_num");
                                detail.usage = readXElement.getSingleTextNotNull("Yt").trim();
                                detail.abstr = pickupAbstr(detail.usage);
                                detail.askNumber = readXElement.getSingleTextNotNull("Check_num").trim();
                                detail.recAccNum = readXElement.getSingleTextNotNull("Rec_Account_num").trim();
                                detail.recAccName = readXElement.getSingleTextNotNull("Unit1_name").trim();
                                detail.recAccBank = readXElement.getSingleTextNotNull("Bank1_name").trim();
                                detail.cur = convertCurToATS(readXElement.getSingleTextNotNull("Account_cur").trim());
                                detail.accBal = converFenToYuan(readXElement.getSingleTextNotNull("Balance").trim());
                                detail.tranAmt = readXElement.getSingleTextNotNull("Amount").trim();
                                detail.cdFlag = readXElement.getSingleTextNotNull("sign").trim();
                                if ("1".equals(detail.cdFlag)) {
                                    if(detail.tranAmt.indexOf("-")>=0) {
                                        detail.cdFlag = "2";
                                        detail.tranAmt = detail.tranAmt.substring(1);
                                    }
                                } else if("2".equals(detail.cdFlag)) {
                                    if(detail.tranAmt.indexOf("-")>=0){
                                        detail.cdFlag = "1";
                                        detail.tranAmt = detail.tranAmt.substring(1);
                                    }
                                }else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "借贷标志( " + detail.cdFlag + ")无法识别，请与银行核对";
                                    break;
                                }
                                detail.tranAmt = converFenToYuan(detail.tranAmt);
                                retAtsTrans.writeRetDetail(detail);
                            }
                            tmpCalendarFrom = tmpClndrStepTo;
                            tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                            tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                            tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
                        } else if ("1".equals(retCode)) {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpBkReader.getFirstText("/ROOT/opRep/opResult/errMsg");
                            break;
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpBkReader.getFirstText("/ROOT/opRep/opResult/errMsg");
                            break;
                        }

                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = bankResult[1];
                    break;
                }
            }
        } catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        } else if (retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespCode("0");
            retAtsTrans.writeRespInfo("交易为空");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

        @Override
        public RetAtsTrans d_7515_TodayTrans (Req7515TodayTrans p_req7515)throws Exception {
            RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7515.reqHeader);
            retAtsTrans.writeStart();
            try {
                String opName = "BSCurDetailOp";
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                writeCommenHeader(xmlTextWriter, opName);
                XElement ReqParam = new XElement("ReqParam","");
                ReqParam.addChild(new XElement("Area_code",p_req7515.actArea));
                ReqParam.addChild(new XElement("Account_num",p_req7515.actNum));
                ReqParam.addChild(new XElement("Account_cur",convertCurToBank(p_req7515.actCur)));
                ReqParam.addChild(new XElement("userID",bankFront.loginName));
                ReqParam.addChild(new XElement("PackageID",getQryTransID()));
                ReqParam.addChild(new XElement("RepReserved1",""));
                ReqParam.addChild(new XElement("RepReserved2",""));
                wirteReqBody(xmlTextWriter, ReqParam, null);
                xmlTextWriter.writeEndDocument();
                String[] bankResult = sendToBank(xmlTextWriter.toXmlString());
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String retCode = tmpBkReader.getFirstText("/ROOT/opRep/opResult/retCode");
                        String Account_num = tmpBkReader.getFirstText("/ROOT/opRep/opResult/retCode");
                        if ("0".equals(retCode)) {
                            while (tmpBkReader.read("/ROOT/opRep/opResultSet/opResult")) {
                                XElement readXElement = tmpBkReader.readedXElement;
                                RetAtsTransDetail detail = new RetAtsTransDetail();
                                detail.tranDate = readXElement.getSingleTextNotNull("Trans_date").substring(0, 10);//yyyy-MM-dd-HH:mm:ss:6位毫秒
                                detail.valueDate = detail.tranDate;
                                detail.actNum = Account_num;
                                detail.tranTime = detail.tranDate+" "+readXElement.getSingleTextNotNull("Trans_date").substring(11, 19);
                                detail.usage = readXElement.getSingleTextNotNull("Yt").trim();
                                detail.abstr = pickupAbstr(detail.usage);
                                detail.askNumber = readXElement.getSingleTextNotNull("Check_num").trim();
                                detail.recAccNum = readXElement.getSingleTextNotNull("Rec_Account_num").trim();
                                detail.recAccName = readXElement.getSingleTextNotNull("Rec_Account_name").trim();
                                detail.recAccBank = readXElement.getSingleTextNotNull("Bank1_code").trim();
                                detail.cur = convertCurToATS(readXElement.getSingleTextNotNull("Account_cur").trim());
                                detail.accBal = converFenToYuan(readXElement.getSingleTextNotNull("Balance").trim());
                                detail.tranAmt = readXElement.getSingleTextNotNull("Amount").trim();
                                detail.cdFlag = readXElement.getSingleTextNotNull("sign").trim();//1借2贷
                                if ("1".equals(detail.cdFlag)) {
                                    if(detail.tranAmt.indexOf("-")>=0) {
                                        detail.cdFlag = "2";
                                        detail.tranAmt = detail.tranAmt.substring(1);
                                    }
                                } else if("2".equals(detail.cdFlag)) {
                                    if(detail.tranAmt.indexOf("-")>=0){
                                        detail.cdFlag = "1";
                                        detail.tranAmt = detail.tranAmt.substring(1);
                                    }
                                }
                                detail.tranAmt = converFenToYuan(detail.tranAmt);
                                retAtsTrans.writeRetDetail(detail);
                            }
                        } else if ("1".equals(retCode)) {
                            retAtsTrans.writeRespCode("-1");
                            retAtsTrans.writeRespInfo(tmpBkReader.getFirstText("/ROOT/opRep/opResult/errMsg"));
                        } else {
                            retAtsTrans.writeRespCode("-1");
                            retAtsTrans.writeRespInfo(tmpBkReader.getFirstText("/ROOT/opRep/opResult/errMsg"));
                        }

                    } else {
                        retAtsTrans.writeRespCode("-1");
                        retAtsTrans.writeRespInfo(tmpSbMsg.toString());
                    }
                } else {
                    retAtsTrans.writeRespCode("-1");
                    retAtsTrans.writeRespInfo(bankResult[1]);
                }

            } catch (Exception ex) {
                retAtsTrans.writeRespCode("-1");
                retAtsTrans.writeRespInfo(ex.getMessage());
                ex.printStackTrace();
            }
            retAtsTrans.writeEnd();
            return retAtsTrans;
        }
}
